import 'dart:convert';

import 'package:coin_genarate/coin_generate.dart';
import 'package:flutter_coin_util/coin_util_import.dart';

class DeFiUtil{
  ///result['interest'] = 0;
  ///result['rate'] = _defaultCoinGenerateEthRate.toString();
  ///result['time'] =  _getCurrentTime();

   DeFiUtil._();

   static DeFiUtil _instance= DeFiUtil._();

   factory DeFiUtil() => _instance;

   /// 获取比例并触发计息，[cEth]是总数
  String getEthExchangeRateAndInterest(double cETH) {
     Map<String,dynamic> map = CoinGenerateManager().getEthExchangeRateAndInterest(cETH);

     _saveInterest(map['time'], map['interest']);

     return map['rate'];
  }

  Future<void> _saveInterest(String time, double interest) async{
     if (interest <= .0)  return;

     dynamic data = await DatabaseUtil.getDefiInterestData(DatabaseUtil.walletNameToTableName(CoinManager.walletName));

     List list = [];

     if (data != null) {
        list = json.decode(data.toString());
     }

     Map<String,dynamic> defiMap = {};
     defiMap['time'] = time;
     defiMap['interest'] = interest;

     list.add(defiMap);
     await DatabaseUtil.saveDefiInterestData(DatabaseUtil.walletNameToTableName(CoinManager.walletName), json.encode(list));
  }

  /// 累计利息，单位为ETH个数
  Future<double> accruedInterest() async {
     double result = .0;

     dynamic data = await DatabaseUtil.getDefiInterestData(DatabaseUtil.walletNameToTableName(CoinManager.walletName));

     if (data == null) return result;

     List list = json.decode(data.toString());

     list.forEach((item) {
        double interest = item["interest"] is double ? item["interest"] : double.tryParse(item["interest"]);
        result += interest;
     });

     return result;
  }


}